import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:hkzf_flutter/dio/community.dart';
import 'package:hkzf_flutter/utils/dio_http.dart';
import 'package:hkzf_flutter/utils/scoped_model_helper.dart';
import 'package:hkzf_flutter/widgets/search_bar/index.dart';
// 小区选择器组件
class CommunityPicker extends StatefulWidget {
  const CommunityPicker({super.key});

  @override
  State<CommunityPicker> createState() => _CommunityPickerState();
}

class _CommunityPickerState extends State<CommunityPicker> {
  List<Community> dataList = [];
  // 搜索查询小区
  _searchHandle(String value) async {
    var areaId =ScopedModelHelper.getAreaId(context);
    var path = '/area/community?id=$areaId&name=$value';
    var res = await DioHttp.of(context).get(path);
    var data = json.decode(res.toString())['body'];
    List<Community> resList = (data as List).map((item)=>Community.fromJson(item)).toList();
    setState(() {
      dataList = resList;
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
      // 隐藏默认返回按钮
      automaticallyImplyLeading: false,
      title: SearchBarWidget(
        showLocation: false,// 隐藏位置按钮
        showMap: false,// 隐藏地图按钮
        onSearchSubmit: (value)=>_searchHandle(value),
        onCancel:(){
           Navigator.of(context).pop();
        },
        goBackCallback: (){
          Navigator.of(context).pop();
        },
      ),
      backgroundColor: Colors.white,
      elevation: 0,
     ),
    body: SafeArea(
      minimum: const EdgeInsets.all(10.0),
      child: ListView.separated(
        itemCount: dataList.length,
        itemBuilder: (context, index){
          return GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: (){
              // 关闭当前页面并将数据返回给上一个页面
              Navigator.of(context).pop(dataList[index]);
            },
            child: Container(
              padding: EdgeInsets.all(5.0),
              child: Text(dataList[index].name),
            ),
          );
        },
        separatorBuilder: (_context, _index)=> const Divider(),
      )
    ),
    );
  }
}